<template>
  <div class="app-container" style="overflow-y: scroll;" v-loading="loading">
    <el-form :model="queryParams" ref="queryRef" :inline="true" :rules="rules">
         <el-form-item label="时间" label-width="40px">
            <WeekTimePicker type="datetime" v-model="queryParams.startTime" format="yyyy-MM-dd HH:mm" :clearable="false" style="width: 160px"/>
            <span style="margin: 0px 6px;">~</span>
            <WeekTimePicker type="datetime" v-model="queryParams.endTime" format="yyyy-MM-dd HH:mm" :clearable="false" style="width: 160px" />
         </el-form-item>
         <el-form-item label="制造区域" prop="factoryAreaId">
            <el-select v-model="queryParams.factoryAreaId" placeholder="区域" style="width: 70px">
               <el-option
                  v-for="dict in factoryAreaIdOptions"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
               />
            </el-select>
         </el-form-item>
         <el-form-item label="制造类型" prop="productionTypeId">
            <el-select v-model="queryParams.productionTypeId" placeholder="制造类型" @change="productionTypeIdChange" style="width: 90px">
               <el-option
                        v-for="dict in listProductionTypeOptions"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
               />
            </el-select>
         </el-form-item>

         <el-form-item label="父设备" prop="topId">
            <el-select v-model="queryParams.topId" placeholder="父设备" @change="topIdChange" style="width: 120px">
               <el-option
                        v-for="dict in topIdOptions"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
               />
            </el-select>
         </el-form-item>

         <!-- 子设备 -->
         <el-form-item label="子设备" prop="machineIdList">
            <el-select v-model="queryParams.machineIdList" multiple
                                clearable
                                collapse-tags
                                collapse-tags-tooltip placeholder="子设备" style="width: 140px">
               <el-option
                        v-for="dict in machineIdListOptions"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
               />
            </el-select>
         </el-form-item>
    </el-form>

    <el-row :gutter="0" class="mb8" style="height: 20px;">
      <el-radio-group v-model="queryParams.radioVal" @change="radioChange" style="margin-bottom: 10px;">
        <el-radio-button label="全部履历"></el-radio-button>
        <el-radio-button label="故障(Down)" ></el-radio-button>
        <el-radio-button label="保养(PM)"></el-radio-button>
        <el-radio-button label="待机(IDLE)"></el-radio-button>
        <el-radio-button label="离线(OFF)"></el-radio-button>
      </el-radio-group>

      <right-toolbar v-model:showSearch="showSearch" @queryTable="handleQuery">
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
          <el-button
              type="success"
              plain
              icon="Sort"
              @click="isShowMethods"
              >状态分析</el-button>
              <!-- @click="(isClickShow = !isClickShow) && isShow " -->
          <!-- <el-button icon="Refresh" @click="resetQuery">重置</el-button> -->
        </el-form-item>
      </right-toolbar>
    </el-row>

    <div v-show="isShow" style=" width: 100%;height: 28px; margin-bottom: 6px; margin-top: 18px;">
      <img src="@/assets/images/legend.jpg" style="display: block; width: 100%; height: 28px;" />
    </div>
     <div id="main" :style="{height}"></div>
     <span class="table_title" v-show="isClickShow">※ 稼动发生时间（分）</span>
     <t-ag-grid
        v-show="isClickShow"
        style="margin: 5px 0px;"
        :style="{height: summaryHeight}"
        :column-defs="columnSummary"
        :row-data="tableDataSummary"
        :row-buffer="20"
        align="center"
        :defaultColDef = "{
            suppressMenu:true
        }"
        header-align="center"
        />

      <span class="table_title" v-show="isClickShow">※ 稼动发生比例（%）</span>
      <t-ag-grid
        v-show="isClickShow"
        style="margin-bottom: 10px; margin-top: 5px;"
        :style="{height: summaryHeight}"
        :column-defs="columnSummaryPercent"
        :row-data="tableDataSummaryPercent"
        :row-buffer="20"
        align="center"
        :defaultColDef = "{
            suppressMenu:true
        }"
        header-align="center"
        />
     <span class="table_title" v-show="isShow">※ 数据总计: {{ tableDataLength }} 条</span>

     <t-ag-grid
          v-show="isShow"
          style="height: calc(100% - 300px);"
          :column-defs="column"
          :row-data="tableData"
          :row-buffer="20"
          :tooltipShowDelay="0"
          align="center"
          :defaultColDef = "{
              menuTabs: ['filterMenuTab', 'columnsMenuTab']
          }"
          header-align="center"
          />
  </div>
</template>

<script setup name="OeeGanttChart">
  import moment from 'moment'
  import * as echarts from 'echarts'
  import { nextTick, onMounted } from 'vue'
  import { queryTableData, chartOptios, getTopId, getSon, allColumn, downColumn, columnSummary, columnSummaryPercent } from './config'
  import { getModelType } from '@/common/affect'

  const { proxy } = getCurrentInstance()

  const rules = {
    factoryAreaId: [{ required: true, message: "制造区域不能为空", trigger: "change" }],
    productionTypeId: [{ required: true, message: "制造类型不能为空", trigger: "change" }],
    topId: [{ required: true, message: "父设备不能为空", trigger: "change" }]
  }

  const queryParams = reactive({
    startTime: moment().subtract(1, 'days').format('YYYY-MM-DD 08:30:00'),
    endTime: moment().format('YYYY-MM-DD 08:30:00'),
    factoryAreaId: '层前',
    productionTypeId: '叠瓦',
    topId: null,
    machineIdList: null,
    radioVal: '全部履历'
  })

  const factoryAreaIdOptions = ref([])
  const listProductionTypeOptions = ref([])
  const topIdOptions = ref([])
  const machineIdListOptions = ref([])

  const showSearch = ref(true)
  let chart = null
  const height = ref('200px')

  const tableData = ref([])
  const column = ref([])
  column.value = allColumn

  const summaryHeight = ref('0px')
  const tableDataSummary = ref([])
  const tableDataSummaryPercent = ref()
  const isShow = ref(false)
  let isClickShow = ref(false)
  const loading = ref(false)

  const tableDataLength = ref()

  getModelType({
    factoryAreaIdList: '层前'
  }).then((res) => {
    res.rows.forEach(item => {
      listProductionTypeOptions.value.push({
        label: item,
        value: item
      })
    })
  })

  getTopId({
    machineType: '叠瓦'
  }).then((res) => {
    res.rows.forEach(item => {
      topIdOptions.value.push({
        label: item,
        value: item
      })
    })
  })

  const productionTypeIdChange = (val) => {
    getTopId({
      machineType: val
    }).then((res) => {
      queryParams.topId = null
      queryParams.machineIdList = null
      topIdOptions.value = []
      machineIdListOptions.value = []
      res.rows.forEach(item => {
        topIdOptions.value.push({
          label: item,
          value: item
        })
      })
    })
  }

  const topIdChange = (val) => {
    getSon({
      machineIdList: val
    }).then((res) => {
      queryParams.machineIdList = []
      machineIdListOptions.value = []
      res.rows.forEach(item => {
        machineIdListOptions.value.push({
          label: item,
          value: item
        })

        queryParams.machineIdList.push(item)
      })
    })
  }

  const _tempObj = {
    "全部履历": 'ALL',
    "故障(Down)": 'DOWN',
    "保养(PM)": 'PM',
    "待机(IDLE)": 'IDLE',
    "离线(OFF)": 'OFF'
  }

  const handleQuery = () => {
    proxy.$refs.queryRef.validate(valid => {
      if(valid){
        if(moment(queryParams.endTime).subtract(16, 'days')>moment(queryParams.startTime)){
          proxy.$modal.alertWarning('最多查询16天的数据')
          return
        }

        if(moment(queryParams.endTime).unix() > moment(moment().subtract(1, 'days').format('YYYY-MM-DD 08:30:00')).unix()
          && moment().unix() < moment(moment().format('YYYY-MM-DD 10:30:00')).unix()
          || moment(queryParams.endTime).unix() > moment(moment().format('YYYY-MM-DD 08:30:00')).unix()){
          proxy.$modal.alertError('1、系统当日OEE履历不可以查询 <br/>2、系统前日OEE履历须在上午10:30以后查询')
          return
        }
        loading.value = true
        queryTableData({
          startTime: moment(queryParams.startTime).format('YYYY-MM-DD HH:mm:ss'),
          endTime: moment(queryParams.endTime).format('YYYY-MM-DD HH:mm:ss'),
          topIdList: queryParams.topId,
          machineIdList: queryParams.machineIdList.join(),
          status: _tempObj[queryParams.radioVal]
        }).then(({ rows }) => {
          loading.value = false

          isShow.value = true
          tableData.value = []
          rows[0].oeeMachineWorkList.forEach((item) => {
            item.keepTime = Number(item.keepTime)
            item.reactTime = Number(item.reactTime)
            item.totalTime = Number(item.totalTime)
            item.totalReactTime = Number(item.totalReactTime)
            tableData.value.push(item)
          })

          tableDataLength.value = rows[0].oeeMachineWorkList.length
          tableDataSummary.value = rows[0].oeeBMachineKindStatusList
          tableDataSummaryPercent.value = rows[0].oeeBMachineKindPerList
          summaryHeight.value = (rows[0].oeeBMachineKindStatusList.length + 1) * 32 + 3 + 'px'

          nextTick(() => {
            chart = echarts.getInstanceByDom(document.getElementById("main"))
            height.value = `${queryParams.machineIdList.length * 60 + 50}px`

            const resizeObserver = new ResizeObserver((entries, b) => {
              if(chart){
                chart.resize()
              }
            })
            resizeObserver.observe(document.getElementById("main"))

            if (chart && chart.dispose) {
              chart.dispose()
            }

            chart = echarts.init(document.getElementById("main"))
            chart.setOption(chartOptios(rows[0].oeeBMachineEchartsList, 'item.mark', 0, moment(queryParams.startTime).format('YYYY-MM-DD HH:mm:ss')), false)
          })
        })
      }
    })
  }

  const radioChange = (val) => {
    if(val === '故障(Down)') {
      column.value = downColumn
    } else {
      column.value = allColumn
    }
    handleQuery()
  }

  const isShowMethods = () => {
    if(isShow.value){
      isClickShow.value = !isClickShow.value
    }
  }

  onMounted(() => {
    chart = echarts.getInstanceByDom(document.getElementById("main"))

    const resizeObserver = new ResizeObserver((entries, b) => {
      if(chart){
        chart.resize()
      }
    })
    resizeObserver.observe(document.getElementById("main"))

    if(!chart){
      chart = echarts.init(document.getElementById("main"))
    }
  })

  const handleExport = () => {
    proxy.download('timeAnalysis/continous/exportAll', {
      startTime: moment(queryParams.startTime).format('YYYY-MM-DD HH:mm:ss'),
      endTime: moment(queryParams.endTime).format('YYYY-MM-DD HH:mm:ss'),
      topIdList: queryParams.topId,
      machineIdList: queryParams.machineIdList.join(),
      status: _tempObj[queryParams.radioVal]
    }, `OEE甘特图_${new Date().getTime()}.xlsx`)
  }

</script>

<style lang="less" scoped>
:deep(.custom-orange) {
  background-color: #ffe699;
}

:deep(.custom-blue) {
  background-color: #bdd7ee;
}

.table_title {
    color: blue;
    font-size: 16px;
    font-weight: 600;
  }
</style>